﻿using System;
using System.Collections.Generic;

namespace Inaction.UI.ComponentModel.Design
{
    public class TypeSelectorEditor<T> : BaseTypeSelectorEditor
    {
        protected override void FillTreeWithData(Selector selector, System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider)
        {
            base.FillTreeWithData(selector, context, provider);
            selector.Clear();
            var assembies = GetDomainAssembies();
            foreach (var assembly in assembies)
            {
                var tagTypes = new List<Type>();
                try
                {
                    var typeList = assembly.GetTypes();
                    foreach (var type in typeList)
                    {
                        if (type is T || type.IsSubclassOf(typeof(T)))
                        {
                            tagTypes.Add(type);
                        }
                    }
                }
                catch (Exception) { continue; }
                
                if (tagTypes.Count != 0)
                {
                    var name = assembly.GetName().Name;
                    var rootNode = selector.AddNode(name, name, null);
                    foreach (var type in tagTypes)
                    {
                        var node = selector.AddNode(type.FullName, type, rootNode);
                        var displayName = type.GetCustomAttribute<System.ComponentModel.DisplayNameAttribute>();
                        if (displayName != null)
                        {
                            node.ToolTipText = displayName.DisplayName;
                        }
                    }
                }
            }
            selector.Sort();
        }

        public override void SetValue(object value)
        {
            if (value is string) return;
            base.SetValue(value as Type);
        }
    }
}